<template>
  <div class="users">
    <el-card class="box-card">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
      <el-form class="user-form" :inline="true">
        <el-form-item>
          <el-input style="width: 350px;" placeholder="请输入内容" v-model="query" @keyup.enter.native="_getUserList">
            <el-button slot="append" icon="el-icon-search" @click='_getUserList'></el-button>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="success" plain @click="userInfoDialog=true">添加用户</el-button>
        </el-form-item>
      </el-form>
      <el-dialog title="添加用户" :visible.sync="userInfoDialog">
        <el-form ref="userInfoForm" :model="userInfoForm">
          <el-form-item 
          prop="username"
          label="用户名" 
          :label-width="formLabelWidth"
          :rules="[
            { required: true, message: '请输入用户名', trigger: 'blur' }
          ]">
            <el-input v-model="userInfoForm.username" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item 
          prop="password"
          label="密码" 
          :label-width="formLabelWidth"
          :rules="[
            { required: true, message: '请输入密码', trigger: 'blur' }
          ]">
            <el-input v-model="userInfoForm.password" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" :label-width="formLabelWidth">
            <el-input v-model="userInfoForm.email" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="电话" :label-width="formLabelWidth">
            <el-input v-model="userInfoForm.mobile" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="userInfoDialog = false">取 消</el-button>
          <el-button type="primary" @click="addUsers">确 定</el-button>
        </div>
      </el-dialog>
      <el-table :data="result.users" style="width: 100%;">
        <el-table-column type="index" label="#" width="50"></el-table-column>
        <el-table-column prop="username" label="姓名" width="100"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
        <el-table-column prop="mobile" label="电话" width="200"></el-table-column>
        <el-table-column prop="create_time" label="创建日期">
          <template slot-scope="scope">{{scope.row.create_time | createTime}}</template>
        </el-table-column>
        <el-table-column prop="mg_state" label="用户状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" active-color="#13ce66" inactive-color="#ff4949" @click.native="setState(scope.row.id,scope.row.mg_state)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="handle" label="操作" width="300">
          <template slot-scope="scope">
            <el-button type="primary" plain size="small" icon="el-icon-edit" circle @click="editUsers(scope.row)"></el-button>
            <el-button type="danger" plain size="small" icon="el-icon-delete" circle @click="removeUsers(scope.row)"></el-button>
            <el-button type="success" plain size="small" icon="el-icon-check" circle @click="rolesUsers(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog title="编辑用户" :visible.sync="edit">
        <el-form :model="editForm">
          <el-form-item 
          prop="name"
          label="用户名" 
          :label-width="formLabelWidth"
          :rules="[
            { required: true, message: '', trigger: 'blur' }
          ]">
            <el-input v-model="editForm.name" autocomplete="off" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" :label-width="formLabelWidth">
            <el-input v-model="editForm.email" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="电话" :label-width="formLabelWidth">
            <el-input v-model="editForm.mobile" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="edit=false">取 消</el-button>
          <el-button type="primary" @click="submitUsers(editForm)">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog title="分配角色" :visible.sync="roles">
        <el-form :model="rolesForm">
          <el-form-item label="用户名" :label-width="formLabelWidth">
            <!-- <el-input v-model="rolesForm.name" autocomplete="off" class="inp-border" :disabled="true"></el-input> -->
            {{rolesForm.name}}
          </el-form-item>
          <el-form-item label="角色" :label-width="formLabelWidth">
            <el-select v-model="rolesForm.rid" placeholder="请选择">
              <el-option :label="item.roleName" :value="item.id" v-for="(item,index) in rolesLists" :key="item.id" :class="index==0&&rolesForm.id!=-1?'optioncolor':''"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="roles = false">取 消</el-button>
          <el-button type="primary" @click="propRoles">确 定</el-button>
        </div>
      </el-dialog>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="+params.pagenum"
        :page-sizes="[2, 4, 6, 8]"
        :page-size="+params.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="result.total">
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
import { getUser, addUsers, updateState, catUsers, submitUsers, removeUsers, rolesList, propRoles} from '../http/api'
export default {
  data() {
    return {
      params: {
        query: this.$route.query.query || '',
        pagenum: this.$route.query.pagenum || 1,
        pagesize: this.$route.query.pagesize || 4
      },
      result: {},
      query: this.$route.query.query || '',
      userInfoForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      userInfoDialog: false,
      formLabelWidth: '100px',
      edit: false,
      editForm: {
        id: "",
        name: '',
        email: '',
        mobile: ''
      },
      roles: false,
      rolesForm: {name: '',id: '', rid: ''},
      rolesLists: []
    }
  },
  methods: {
    async getUserList(){ //获取用户列表
      if (this.$route.query.query) {
        const res = await getUser(this.params)
        this.result=res.data;
      } else {
        const {pagenum, pagesize} = this.params;
        const res = await getUser({pagenum, pagesize});
        this.result=res.data;
      }
    },
    handleSizeChange(num) { //每页显示条数发生变化时触发
      this.params.pagesize=num;
      this.getUserList();
    },
    handleCurrentChange(num) { //页码发生变化
      this.params.pagenum=num;
      this.getUserList();
    },
    addUsers(){ //添加用户
      // 表单验证
      this.$refs.userInfoForm.validate(async(valid)=>{
        if (valid) {
          const res = await addUsers(this.userInfoForm)
          // console.log(res)
          //请求成功或失败的弹框提示
          this.$message({ 
            showClose: true,
            message: res.meta.msg,
            type: 'success'
          })
          // 关闭添加用户弹框
          this.userInfoDialog=false;
          // 清空添加用户弹框的内容
          this.$refs.userInfoForm.resetFields();
          this._getUserList();
          this.getUserList();
        }
      })
    },
    async _getUserList(){ //查询用户,排除query
      this.params.pagenum=1;
      this.params.query=this.query;
      const res = await getUser(this.params);
      this.result = res.data;
    },
    async setState(id,state){ //设置用户状态
      const res=await updateState({uId: id,type: state})
      // console.log(res,id,state);
      this.$message({ 
        showClose: true,
        message: res.meta.msg,
        type: 'success'
      })
    },
    editUsers(obj){ //编辑时显示用户信息
      this.edit=true;
      this.editForm.id=obj.id;
      this.editForm.name=obj.username;
      this.editForm.email=obj.email;
      this.editForm.mobile=obj.mobile;
    },
    async catUsers(id){ //根据id查询用户信息
      const res=await catUsers(id)
      console.log(res);
      this.rolesForm.id = res.data.rid;
    },
    submitUsers(obj){ //用户提交
      this.edit=false;
      const {id,email,mobile} = obj
      const data = {email, mobile}
      return submitUsers(id,data).then(res=>{
        // console.log(res);
        this.$message({ 
          showClose: true,
          message: res.meta.msg,
          type: 'success'
        })
        this.getUserList();
      })
    },
    removeUsers(obj){ //删除单个用户
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        return removeUsers(obj.id).then(res=>{
          // console.log(res)
          this.$message({
            showClose: true,
            type: 'success',
            message: res.meta.msg
          });
          this.getUserList();
        })
      }).catch(() => {
        this.$message({
          showClose: true,
          type: 'info',
          message: 'catch--'
        });
      });
    },
    async rolesUsers(obj){ //编辑角色显示信息
      const {id,username} = obj;
      this.roles=true;
      const { rid } =await catUsers(id);
      // console.log(res)
      this.rolesForm.id=id;
      this.rolesForm.name=username;
      this.rolesForm.rid=rid;
      this.rolesList();
    },
    rolesList(){ //角色列表
      return rolesList().then(res=>{
        console.log(res);
        this.rolesLists=res.data;
        this.rolesLists.unshift({id: -1,roleName: '请选择'})
      })
    },
    async propRoles(){ //分配用户角色
        // console.log(this.rolesForm)
      try {
        const {id, rid} = this.rolesForm;
        const res=await propRoles(id, rid);
        console.log(res)
        this.roles=false;
        this.$message({
            showClose: true,
            message: res.meta.msg,
            type: 'success'
        })
        this.getUserList();
      } catch (error) {
        console.log(error)
      }
    }
  },
  watch:{
    params:{ //监听params并传入路径
      deep: true,
      handler(val){
        this.$router.push({query: val});
      }
    }
  },
  created(){
    this.getUserList();
  },
  filters:{
    createTime(item){ //将毫秒数过滤为日期
      var mouth = new Date(item).getMonth()+1;
      if (mouth<10) {
        mouth = '0' + mouth;
      }
      item = new Date(item).getFullYear() + '-' + mouth + '-'+ new Date(item).getDate();
      return item;
    }
  }
}
</script>

<style scoped lang="scss">
.users{
  height: 100%;  
  .box-card{
    width: 100%;
    height: 100%;
  } 
}
.user-form {
  display: flex;
  align-items: center;
  margin: 10px 0;
  .el-form-item{
    margin-bottom: 0;
    margin-right: 5px;
  }
}
.optioncolor{
  color: #c0c4cc;
}
</style>
